#pragma once

#include <cstdlib>
#include <iostream>
#include <memory>
#include <jsoncpp/json/json.h>
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonRequest.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/CommonResponse.h>
#include "logger.h"

class DMSClient
{
public:
    using ptr = std::shared_ptr<DMSClient>;

    DMSClient(const std::string &access_key_id, const std::string &access_key_secret)
    {
        AlibabaCloud::InitializeSdk();
        AlibabaCloud::ClientConfiguration configuration("cn-chengdu");
        // specify timeout when create client.
        configuration.setConnectTimeout(1500);
        configuration.setReadTimeout(4000);
        AlibabaCloud::Credentials credential(access_key_id, access_key_secret);
        _cli = std::make_unique<AlibabaCloud::CommonClient>(credential, configuration);
    }

    bool send(const std::string &phone_num, const std::string &code)
    {
        AlibabaCloud::CommonRequest request(AlibabaCloud::CommonRequest::RequestPattern::RpcPattern);
        request.setHttpMethod(AlibabaCloud::HttpRequest::Method::Post);
        request.setDomain("dysmsapi.aliyuncs.com");
        request.setVersion("2017-05-25");
        request.setQueryParameter("Action", "SendSms");
        request.setQueryParameter("SignName", "聊天服务器");
        request.setQueryParameter("TemplateCode", "SMS_475880703");
        request.setQueryParameter("PhoneNumbers", phone_num);
        std::string param_code = "{\"code\":\"" + code + "\"}";
        request.setQueryParameter("TemplateParam", param_code);

        auto response = _cli->commonResponse(request);
        if (!response.isSuccess())
        {
            LOG_ERROR("短信验证码请求失败：{}", response.error().errorMessage());
            return false;
        }
        return true;
    }

    ~DMSClient()
    {
        AlibabaCloud::ShutdownSdk();
    }

private:
    std::unique_ptr<AlibabaCloud::CommonClient> _cli;
};